package com.nekonomics
package schedule

import domain.service.{OrderService, PaymentService}

import zio.*
import zio.stream.ZStream


object TradeScheduler {
  val autoDelivered =
    ZStream.fromSchedule(Schedule.fixed(2.minutes))
      .mapZIO { _ =>
        ZIO.logInfo("订单到达") *>
          ZIO.serviceWithZIO[OrderService](_.orderDelivered())
      }
      .runDrain


  val autoClosed =
    ZStream.fromSchedule(Schedule.fixed(1.minutes))
      .mapZIO { _ =>
        ZIO.logInfo("开始清理超时订单") *>
          ZIO.serviceWithZIO[PaymentService](_.closeExpiredPaymentAndOrders())
            .logError
            .catchAll(e => ZIO.logError(s"关闭订单失败: $e"))
      }
      .runDrain



  val launch = for {
    _ <- autoDelivered.forkDaemon
    _ <- autoClosed.forkDaemon
  } yield ()

}
